package com.higgins.eventtracking.client.health.record.entry;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.visualizations.LineChart;
import com.google.gwt.visualization.client.visualizations.LineChart.Options;
import com.higgins.eventtracking.client.EventTrackingService;
import com.higgins.eventtracking.client.EventTrackingServiceAsync;
import com.higgins.eventtracking.client.FinanceTrackingService;
import com.higgins.eventtracking.client.FinanceTrackingServiceAsync;
import com.higgins.eventtracking.client.SecurityAccessDeniedException;
import com.higgins.eventtracking.client.dto.DynamicTypeDTO;
import com.higgins.eventtracking.client.dto.HealthStatsDTO;
import com.higgins.eventtracking.client.dto.TrackingEventDTO;
import com.higgins.eventtracking.client.health.components.GenericChartPanel;
import com.higgins.eventtracking.client.health.components.GenericTabInterface;

public class Exercise extends VerticalPanel	implements GenericTabInterface		{
	private static final String SERVER_ERROR = "An error occurred while "
		+ "attempting to contact the server. Please check your network "
		+ "connection and try again.";

	private final EventTrackingServiceAsync greetingService = GWT
			.create(EventTrackingService.class);
	private final FinanceTrackingServiceAsync financeTrackingService = GWT
				.create(FinanceTrackingService.class);
	
	private final ListBox eventTypeList = new ListBox();
	
	private final Label distanceLabel = new Label("Distance: ");
	private final Label minutesLabel = new Label("Minutes: ");
	private final Label secondsLabel = new Label("Seconds: ");
	private final Label weightLabel = new Label("Weight: ");
	private final Label repsLabel = new Label("Reps: ");
	private final Label error = new Label();
	
	private final TextBox distanceField = new TextBox();
	private final TextBox minutesField = new TextBox();
	private final TextBox secondsField = new TextBox();
	private final TextBox weightField = new TextBox();
	private final TextBox repsField = new TextBox();
	
	private final Button sendButton = new Button("Add");
	private boolean firstRun = true;
	private Integer tabIndex = null;
	private String tabTitle = null;
	
	@Override
	public Integer getTabIndex() {
		return tabIndex;
	}
	@Override
	public void setTabIndex(Integer index) {
		this.tabIndex = index;
	}
	@Override
	public String getTabTitle()	{
		return tabTitle;
	}
	@Override
	public void setTabTitle(String tabTitle)	{
		this.tabTitle = tabTitle;
	}

	public Exercise()	{
	}
	
	public void update()	{
		if (firstRun)	
			initialise();
		
	}

	private void populateExerciseTypes()	{
		eventTypeList.addItem("------");
		try {
			financeTrackingService.retrieveDynamicTypes("ExerciseType", new AsyncCallback<List<DynamicTypeDTO>>()  {

				@Override
				public void onFailure(Throwable caught) {
					eventTypeList.addItem("Failed!!!");

				}

				@Override
				public void onSuccess(List<DynamicTypeDTO> result) {
					for (DynamicTypeDTO dto:result)	{
						if (dto.getSubType()!=null && dto.getSubType().equals(true))
						eventTypeList.addItem(dto.getSubCategory());
					}
					
				} });
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityAccessDeniedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
//		eventTypeList.addItem("Stretching");
//		eventTypeList.addItem("Squats");		
//		eventTypeList.addItem("Deadlifts");		
//		eventTypeList.addItem("Leg Extension");
//		eventTypeList.addItem("Leg Curls");
//		eventTypeList.addItem("Delts Vertical");		
//		eventTypeList.addItem("Delts Butterfly");		
//		eventTypeList.addItem("Delts Rear");		
//		eventTypeList.addItem("Abs");		
//		eventTypeList.addItem("Obliques");		
//		eventTypeList.addItem("Ab Twists");		
//		eventTypeList.addItem("Pull-overs");		
//		eventTypeList.addItem("Barbell Rows");		
//		eventTypeList.addItem("Bench Press");		
//		eventTypeList.addItem("Lower Back");		
//		eventTypeList.addItem("Bicep Curls");		
//		eventTypeList.addItem("Triceps Exts");		
//		eventTypeList.addItem("Upper Back");		
//		eventTypeList.addItem("Walking");
//		eventTypeList.addItem("Cycling");
//		eventTypeList.addItem("Running");
//		eventTypeList.addItem("Swimming");			
	}
	
	public void initialise()	{
		firstRun = false;
		populateExerciseTypes();
		
		distanceField.setText("0.0");
		minutesField.setText("0");
		secondsField.setText("0");
		weightField.setText("0.0");
		repsField.setText("0");
		
		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		add(eventTypeList);
		add(sendButton);
		
		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler, ChangeHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendTrackingEventToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendTrackingEventToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendTrackingEventToServer() {
				// First, we validate the input.
				Double distance = 0.0;
				Integer minutes = 0;
				Integer seconds = 0;
				Double weight = 0.0;
				Integer reps = 0;
				
				distance = new Double(distanceField.getText());
				minutes = new Integer(minutesField.getText());
				seconds = new Integer(secondsField.getText());
				weight = new Double(weightField.getText());
				reps = new Integer(repsField.getText());

				
				TrackingEventDTO dto = new TrackingEventDTO();
				dto.setEventType(eventTypeList.getItemText(eventTypeList.getSelectedIndex()));
				dto.setTimeStamp(new Date());
				dto.setDistance(distance);
				dto.setMinutes(minutes);
				dto.setSeconds(seconds);
				dto.setWeight(weight);
				dto.setReps(reps);
				
				sendButton.setEnabled(false);
				greetingService.insertTrackingEvent(dto,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								sendButton.setEnabled(true);
								error.setText("FAILURE");
							}

							public void onSuccess(String result) {
								sendButton.setEnabled(true);
								error.setText("SUCCESS");
							}
						});
			}
	
			private void setFieldsToBlank()	{
				distanceField.setText("");
				minutesField.setText("");
				secondsField.setText("");
				weightField.setText("");
				repsField.setText("");
				error.setText("");
			}
			private void setFieldsToZero()	{
				distanceField.setText("0.0");
				minutesField.setText("0");
				secondsField.setText("0");
				weightField.setText("0.0");
				repsField.setText("0");
				error.setText("");
			}
			private void blankCardioFields()	{
				Iterator<Widget> iterator = iterator();
				while (iterator.hasNext())	{
					Widget widget = iterator.next();
					remove(widget);
				}
				
				remove(distanceLabel);
				remove(minutesLabel);
				remove(secondsLabel);
				remove(weightLabel); 
				remove(repsLabel); 
				
				add(eventTypeList);
				add(sendButton);
				add(error);
				setFieldsToBlank();
				
			}			
			private void displayCardioFields()	{
				Iterator<Widget> iterator = iterator();
				while (iterator.hasNext())	{
					Widget widget = iterator.next();
					remove(widget);
				}
				
				remove(distanceLabel);
				remove(minutesLabel);
				remove(secondsLabel);
				remove(weightLabel); 
				remove(repsLabel); 
				
				add(eventTypeList);
				add(distanceLabel);
				add(distanceField);
				add(minutesLabel);
				add(minutesField);
				add(secondsLabel);
				add(secondsField);
				add(sendButton);
				add(error);
				setFieldsToBlank();
				
			}
			private void displayAnabolicFields()	{
				Iterator<Widget> iterator = iterator();
				while (iterator.hasNext())	{
					Widget widget = iterator.next();
					remove(widget);
				}
				remove(distanceLabel);
				remove(minutesLabel);
				remove(secondsLabel);
				remove(weightLabel); 
				remove(repsLabel); 
				
				add(eventTypeList);
				add(weightLabel);
				add(weightField);
				add(repsLabel);
				add(repsField);
				add(sendButton);
				add(error);
				setFieldsToBlank();
			}

			@Override
			public void onChange(ChangeEvent event) {
				if (eventTypeList.getItemText(eventTypeList.getSelectedIndex()).equals("Stretching")) 	{
					blankCardioFields();
				} else if (
					eventTypeList.getItemText(eventTypeList.getSelectedIndex()).equals("Walking") ||
					eventTypeList.getItemText(eventTypeList.getSelectedIndex()).equals("Cycling") || 
					eventTypeList.getItemText(eventTypeList.getSelectedIndex()).equals("Running") || 
					eventTypeList.getItemText(eventTypeList.getSelectedIndex()).equals("Swimming"))	{
					displayCardioFields();
				} else {
					displayAnabolicFields();
				}
				
				// RETRIEVE LAST RECORD HERE!!!! THEN SET THE TEXT BOXES
				greetingService.retrieveTrackingEvent(eventTypeList.getItemText(eventTypeList.getSelectedIndex()),
						new AsyncCallback<TrackingEventDTO>() {
							public void onFailure(Throwable caught) {
								setFieldsToZero();								
							}

							@SuppressWarnings("unused")
							public void onSuccess(TrackingEventDTO result) {
								setFieldsToZero();								
								if (result!=null)	{
									distanceField.setText(result.getDistance().toString());
									minutesField.setText(result.getMinutes().toString());
									secondsField.setText(result.getSeconds().toString());
									weightField.setText(result.getWeight().toString());
									repsField.setText(result.getReps().toString());
								}	else	{
									distanceField.setText("0.0");
									minutesField.setText("0");
									secondsField.setText("0");
									weightField.setText("0.0");
									repsField.setText("0");
								}
							}
						});
				
				
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		eventTypeList.addChangeHandler(handler);
	}
	@Override
	public void addChartPanel(GenericChartPanel chartPanel) {
		// TODO Auto-generated method stub
		
	}

}
